from django.contrib.auth.models import AnonymousUser
from django.utils.deprecation import MiddlewareMixin
import datetime


### 自定义中间件解决跨域问题---》以后其它框架都是这个原理---》django上有人做了


class CorsMiddleware(MiddlewareMixin):
    def process_response(self, request, response):
        if request.method == 'OPTIONS':
            response['Access-Control-Allow-Headers'] = 'token'
            response['Access-Control-Allow-Methods'] = 'DELETE,PUT'
        response['Access-Control-Allow-Origin'] = '*'
        return response


from user import models
from user_agents import parse


### 自定义中间件解决跨域问题---》以后其它框架都是这个原理---》django上有人做了
class GETCLICETYPE(MiddlewareMixin):
    def process_request(self, request):
        # 浏览器类型
        bw = request.META['HTTP_USER_AGENT']
        # ip
        ip = request.META['REMOTE_ADDR']
        # 时间
        timer = datetime.datetime.now()
        # 用户访问的地址，
        url = request.path
        user = request.user
        # print(bw)
        user_agent = parse(bw)
        # print(user_agent.device.family)
        # print(user_agent.device.model)

        try:
            models.ClientType.objects.create(bw=user_agent.device.family,  ip=ip, url=url, user=user)
        except Exception:
            models.ClientType.objects.create(bw=user_agent.device.family,  ip=ip, url=url)
